package cn.fuxi2022.module.info.controller;

import cn.fuxi2022.commons.redis.service.CaptchaService;
import cn.fuxi2022.core.exception.SmartGroupException;
import cn.fuxi2022.core.utils.JwtUtils;
import cn.fuxi2022.feign.api.GroupAuth;
import cn.fuxi2022.feign.api.GroupStudent;
import cn.fuxi2022.model.empty.applets.GroupStudentInfo;
import cn.fuxi2022.model.empty.applets.GroupStudentPayLog;
import cn.fuxi2022.model.resp.PageUtils;
import cn.fuxi2022.model.resp.R;
import cn.fuxi2022.model.vo.admin.GroupStudentAdminVo;
import cn.fuxi2022.model.vo.applets.GroupStudentInfoVo;
import cn.fuxi2022.module.info.service.GroupStudentInfoService;
import cn.fuxi2022.module.pay.service.GroupStudentPayLogService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 社员详细信息表
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2022-09-24 19:57:36
 */
@RestController
@RequestMapping("admin/studentInfo")
public class GroupStudentInfoController {
    @Autowired
    private GroupStudentInfoService groupStudentInfoService;

    @Autowired
    private GroupStudent groupStudent;

    /**
     * 根据学生ID获取学生信息
     */
    @GetMapping("/getGroupStudentInfoByStudentId/{studentId}")
    public GroupStudentInfo getGroupStudentInfoByStudentId(@PathVariable("studentId") String studentId) {
        LambdaQueryWrapper<GroupStudentInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GroupStudentInfo::getStudentId, studentId);
        return groupStudentInfoService.getOne(wrapper);
    }

    // ---------------------------------------------------------

    /**
     * 列表
     */
    @PostMapping("/list")
    public R list(@RequestBody Map<String, Object> params) {
        // 根据分页获取学生列表
        PageUtils groupStudentPageUtils = groupStudent.list(params);
        List<?> list = groupStudentPageUtils.getList();
        List<GroupStudentAdminVo> groupStudentAdminVoList = list.stream().map(
                (Function<Object, GroupStudentAdminVo>) o -> {
                    // 1.获取学生ID
                    Map map = (Map) o;
                    String id = (String) map.get("id");
                    // 2.根据学生ID查询学生信息
                    LambdaQueryWrapper<GroupStudentInfo> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(GroupStudentInfo::getStudentId, id);
                    GroupStudentInfo groupStudentInfo = groupStudentInfoService.getOne(wrapper);

                    // 3.创建前端VO对象
                    GroupStudentAdminVo groupStudentAdminVo = new GroupStudentAdminVo();
                    groupStudentAdminVo.setMobile((String) map.get("mobile"));
                    groupStudentAdminVo.setStudentId(id);

                    // 4.如果学生的openid不存在，说明只是登录还没有授权，只是登录
                    if (ObjectUtils.isEmpty(map.get("openidGz"))) {
                        groupStudentAdminVo.setStage(0);
                        return groupStudentAdminVo;
                    }

                    // 5.如果学生的基本信息不存在，说明登录成功，但是还没有开始入社
                    if (ObjectUtils.isEmpty(groupStudentInfo)) {
                        groupStudentAdminVo.setStage(1);
                        return groupStudentAdminVo;
                    }

                    // 6.拷贝对象，将学生信息拷贝
                    BeanUtils.copyProperties(groupStudentInfo, groupStudentAdminVo);

                    // 7.设置阶段（0登录未完善 1信息未录入 2未支付社费 3未加群 4完成）
                    groupStudentAdminVo.setStage(groupStudentInfo.getIsStudent() + 1);

                    // 8.若入社完成，设置完成的时间
                    if (groupStudentInfo.getIsStudent() == 3) {
                        groupStudentAdminVo.setTime(groupStudentInfo.getGmtModified());
                    }

                    return groupStudentAdminVo;
                }).collect(Collectors.toList());

        groupStudentPageUtils.setList(groupStudentAdminVoList);

        return R.ok().data(groupStudentPageUtils);
    }

    // ---------------------------------------------------------

    /**
     * 获取
     */
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") String id) {
        GroupStudentInfo groupStudentInfo = groupStudentInfoService.getById(id);
        return R.ok().data("groupStudentInfo", groupStudentInfo);
    }

    /**
     * 修改
     */
    @PutMapping("/update/{id}")
    public R update(@PathVariable("id") String id, @RequestBody @Validated GroupStudentInfoVo groupStudentInfoVo) {
        GroupStudentInfo studentInfo = new GroupStudentInfo();
        studentInfo.setId(id);
        BeanUtils.copyProperties(groupStudentInfoVo, studentInfo);
        groupStudentInfoService.saveOrUpdate(studentInfo);
        return R.ok("修改社员信息成功");
    }

    @Autowired
    private GroupAuth groupAuth;


    @GetMapping("/delete/captcha")
    public R deleteSendCaptcha(HttpServletRequest httpServletRequest) {
        // 当前的管理员用户
        String id = JwtUtils.getMemberIdByJwtToken(httpServletRequest);
        // 获取当前用户的手机号
        String phone = groupAuth.getPhoneById(id);
        // 发送验证码
        groupStudentInfoService.getCaptcha(phone);
        return R.ok("发送验证码成功");
    }

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private GroupStudentPayLogService groupStudentPayLogService;

    /**
     * 删除
     */
    @DeleteMapping("/delete/{id}/{code}")
    public R delete(@PathVariable("id") String studentId, @PathVariable("code") String code, HttpServletRequest httpServletRequest) {
        // 当前的管理员用户
        String id = JwtUtils.getMemberIdByJwtToken(httpServletRequest);
        // 获取当前用户的手机号
        String phone = groupAuth.getPhoneById(id);

        // 判断验证码是否合法
        if (!captchaService.checkCaptcha(code, phone)) {
            throw new SmartGroupException("验证码错误，请重新输入");
        }
        // 删除社员信息
        LambdaQueryWrapper<GroupStudentInfo> groupStudentInfoWrapper = new LambdaQueryWrapper<>();
        groupStudentInfoWrapper.eq(GroupStudentInfo::getStudentId, studentId);
        groupStudentInfoService.remove(groupStudentInfoWrapper);
        // 删除社员
        groupStudent.delete(studentId);
        // 删除支付信息
        LambdaQueryWrapper<GroupStudentPayLog> groupStudentPayLogWrapper = new LambdaQueryWrapper<>();
        groupStudentPayLogWrapper.eq(GroupStudentPayLog::getStudentId, studentId);
        groupStudentPayLogService.remove(groupStudentPayLogWrapper);
        return R.ok("退社成功");
    }

    @GetMapping("/update/captcha/{newPhone}")
    public R updatePhoneSendCaptcha(@PathVariable("newPhone") String newPhone) {
        // 发送验证码
        groupStudentInfoService.getCaptcha(newPhone);
        return R.ok("发送验证码成功");
    }

    /**
     * 修改
     */
    @PutMapping("/update/{id}/{phone}/{code}")
    public R updatePhoneById(@PathVariable("id") String id, @PathVariable("phone") String phone, @PathVariable("code") String code) {
        // 判断验证码是否合法
        if (!captchaService.checkCaptcha(code, phone)) {
            throw new SmartGroupException("验证码错误，请重新输入");
        }

        cn.fuxi2022.model.empty.auth.GroupStudent groupStudentObj = new cn.fuxi2022.model.empty.auth.GroupStudent();
        groupStudentObj.setId(id);
        groupStudentObj.setMobile(phone);

        groupStudent.update(groupStudentObj);

        return R.ok("修改社员手机号成功");
    }
}
